<template>
    <el-dialog v-model="dialogFormVisible" title="数据填写">
        <el-form :model="form" label-position="top" label-width="auto" :inline="true" :rules="rules" ref="ruleFormRef"
            v-loading="isLoading">
            <el-form-item :label="item.fieldCnNm" :prop="item.fieldEnNm" v-for="item in fields" :key="item.id"
                :style="(item.fieldType === '1' || item.fieldType === '6' || item.fieldType === '7'
                    || item.fieldType === '9' || item.fieldType === '10' || item.fieldType === '11') ? 'width: 100%;' : ''">
                <el-input clearable v-model="form[item.fieldEnNm]" :placeholder="'请输入' + item.fieldCnNm"
                    style="width: 200px" v-if="item.fieldType === '0'" />
                <el-input type="textarea" v-model="form[item.fieldEnNm]" :placeholder="'请输入' + item.fieldCnNm"
                    v-else-if="item.fieldType === '1'" :rows="4" />
                <el-input clearable v-model="form[item.fieldEnNm]" :placeholder="'请输入' + item.fieldCnNm"
                    style="width: 200px" v-else-if="item.fieldType === '2'">
                    <template #append>
                        {{ item.fieldConf }}
                    </template>
                </el-input>
                <el-date-picker v-model="form[item.fieldEnNm]" type="date" :placeholder="'请选择' + item.fieldCnNm"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 200px"
                    v-else-if="item.fieldType === '3'" />
                <el-time-picker v-model="form[item.fieldEnNm]" :placeholder="'请选择' + item.fieldCnNm" format="HH:mm:ss"
                    value-format="HH:mm:ss" style="width: 200px" v-else-if="item.fieldType === '4'" />
                <el-date-picker v-model="form[item.fieldEnNm]" type="datetime" :placeholder="'请选择' + item.fieldCnNm"
                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 200px"
                    v-else-if="item.fieldType === '5'" />
                <div v-else-if="item.fieldType === '6'">
                    <el-upload v-model:file-list="item.pictureList"
                        :class="{ disableUpload: item.pictureList.length > 2 }"
                        :before-upload="(uploadFile) => beforeAvatarUpload(uploadFile, true)" :headers="header"
                        :action="action" :on-preview="(uploadFile) => handlePictureCardPreview(uploadFile, item.id)"
                        :on-remove="(uploadFile, uploadFiles) => handleRemove(uploadFile, uploadFiles, item.fieldEnNm)"
                        :on-success="(response, uploadFile, uploadFiles) => handleAvatarSuccess(response, uploadFile, uploadFiles, item.fieldEnNm)"
                        list-type="picture-card" :limit="3">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="item.dialogVisible">
                        <img style="height: 100%; width: 100%;" w-full :src="item.dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </div>
                <el-upload v-model:file-list="item.fileList" :headers="header" :action="action" multiple :limit="1"
                    :before-upload="(uploadFile) => beforeAvatarUpload(uploadFile, false)"
                    :on-remove="(uploadFile, uploadFiles) => handleRemove(uploadFile, uploadFiles, item.fieldEnNm)"
                    :on-success="(response, uploadFile, uploadFiles) => handleAvatarSuccess(response, uploadFile, uploadFiles, item.fieldEnNm)"
                    v-else-if="item.fieldType === '7'">
                    <el-button type="primary" plain :disabled="item.fileList.length > 0">点击上传</el-button>
                </el-upload>
                <el-select v-model="form[item.fieldEnNm]" clearable :placeholder="'请选择' + item.fieldCnNm"
                    style="width: 200px" v-else-if="item.fieldType === '8'">
                    <el-option v-for="dictItem in item.options" :key="dictItem.code" :label="dictItem.value"
                        :value="dictItem.code" />
                </el-select>
                <el-radio-group v-model="form[item.fieldEnNm]" v-else-if="item.fieldType === '9'">
                    <el-radio v-for="dictItem in item.options" :value="dictItem.code">{{ dictItem.value }}</el-radio>
                </el-radio-group>
                <el-rate v-model="form[item.fieldEnNm]" v-else-if="item.fieldType === '10'" />
                <div v-else-if="item.fieldType === '11'">
                    <div class="fun">
                        <el-button type="primary" plain size="small"
                            @click="form[item.fieldEnNm].push({})">添加行+</el-button>
                    </div>
                    <div class="table" :style="$isMobile() ? 'width:87vw' : 'width:47vw'">
                        <el-table border empty-text="请添加行" :data="form[item.fieldEnNm]"
                            :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }">
                            <el-table-column :prop="tableField.fieldEnNm" :label="tableField.fieldCnNm" min-width="150"
                                v-for="tableField in item.tableFields" :key="tableField.id">
                                <template #default="{ row }">
                                    <el-input size="small" clearable v-model="row[tableField.fieldEnNm]"
                                        :placeholder="'请输入' + tableField.fieldCnNm"
                                        v-if="tableField.fieldType === '0'" />
                                    <el-input size="small" clearable v-model="row[tableField.fieldEnNm]"
                                        :placeholder="'请输入' + tableField.fieldCnNm" v-if="tableField.fieldType === '2'">
                                        <template #append>
                                            {{ tableField.fieldConf }}
                                        </template>
                                    </el-input>
                                    <el-date-picker size="small" v-model="row[tableField.fieldEnNm]" type="date"
                                        :placeholder="'请选择' + tableField.fieldCnNm" format="YYYY-MM-DD"
                                        value-format="YYYY-MM-DD" v-else-if="tableField.fieldType === '3'"
                                        style="width: 125px" />
                                    <el-time-picker size="small" v-model="row[tableField.fieldEnNm]"
                                        :placeholder="'请选择' + tableField.fieldCnNm" format="HH:mm:ss"
                                        value-format="HH:mm:ss" v-else-if="tableField.fieldType === '4'"
                                        style="width: 125px" />
                                    <el-date-picker size="small" v-model="row[tableField.fieldEnNm]" type="datetime"
                                        :placeholder="'请选择' + tableField.fieldCnNm" format="YYYY-MM-DD HH:mm:ss"
                                        value-format="YYYY-MM-DD HH:mm:ss" v-else-if="tableField.fieldType === '5'"
                                        style="width: 125px" />
                                    <el-select size="small" v-model="row[tableField.fieldEnNm]" clearable
                                        :placeholder="'请选择' + tableField.fieldCnNm"
                                        v-else-if="tableField.fieldType === '8'">
                                        <el-option v-for="dictItem in tableField.options" :key="dictItem.code"
                                            :label="dictItem.value" :value="dictItem.code" />
                                    </el-select>
                                    <el-radio-group size="small" v-model="row[tableField.fieldEnNm]"
                                        v-else-if="tableField.fieldType === '9'">
                                        <el-radio v-for="dictItem in tableField.options" :value="dictItem.code">{{
                                            dictItem.value }}</el-radio>
                                    </el-radio-group>
                                </template>
                            </el-table-column>
                            <el-table-column :fixed="$isMobile() ? false : 'right'" label="操作" width="80">
                                <template #default="scope">
                                    <el-button text type="primary" size="small"
                                        @click="form[item.fieldEnNm].splice(scope.$index, 1)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">返回</el-button>
                <el-button :disabled="isLoading" type="primary" @click="submit" v-if="!disabledSubmit">提交流程</el-button>
            </div>
        </template>
        <workflowSubmit ref="wf" @serversUpdated="dialogFormVisible = false"></workflowSubmit>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import api from "@/api"
import { ElMessage } from 'element-plus'
import { Decrypt } from '@/utils/secret.js'
import workflowSubmit from "./workflowSubmit.vue";

const isLoading = ref(false)
const ruleFormRef = ref()
const dialogFormVisible = ref(false)
const form = ref({})
const definitionId = ref()
const instanceId = ref()
const fields = ref([])
const action = ref(import.meta.env.VITE_BASE_URL + '/system/file/upload?business=审批文件上传')
const header = ref()
const wf = ref()
const rules = ref({})
const disabledSubmit = ref(false)
//实例ID为空表示发起流不为空表示重新发起流
const init = async (defId, insId) => {
    dialogFormVisible.value = true
    isLoading.value = true
    fields.value = []
    form.value = {}
    definitionId.value = defId
    instanceId.value = insId
    const res = await api.post('/workflow/businessField/getFields', { definitionId: defId })
    if (res.data.code === 200) {
        fields.value = res.data.data
        handleField(fields.value)
        //存在实例ID查询该实例展示数据
        if (insId) {
            const res = await api.post('/workflow/businessData/getData', { instanceId: insId })
            if (res.data.code === 200) {
                if (res.data.data) {
                    form.value = res.data.data
                }
            } else {
                ElMessage.error(res.data.msg)
            }
            fields.value.forEach(item => {
                //处理图片
                if (item.fieldType === '6') {
                    item.pictureList = []
                    item.dialogImageUrl = ''
                    item.dialogVisible = false
                    if (form.value[item.fieldEnNm]) {
                        const valueArr = form.value[item.fieldEnNm].split(",");
                        valueArr.forEach(valueItem => {
                            item.pictureList.push(
                                {
                                    name: decodeURIComponent(escape(atob(valueItem))),
                                    response: {
                                        data: valueItem
                                    },
                                    url: import.meta.env.VITE_BASE_URL + '/system/file/download/' + valueItem
                                })
                        })
                    }
                    //处理文件
                } else if (item.fieldType === '7') {
                    item.fileList = []
                    if (form.value[item.fieldEnNm]) {
                        const valueArr = form.value[item.fieldEnNm].split(",");
                        valueArr.forEach(valueItem => {
                            item.fileList.push(
                                {
                                    name: decodeURIComponent(escape(atob(valueItem))),
                                    response: {
                                        data: valueItem
                                    },
                                    url: import.meta.env.VITE_BASE_URL + '/system/file/download/' + valueItem
                                })
                        })
                    }
                }
            })
        }
    } else {
        ElMessage.error(res.data.msg)
    }
    isLoading.value = false
}

//处理字段
const handleField = (fields) => {
    fields.forEach(async item => {
        rules.value[item.fieldEnNm] = []
        if (item.requiredFlag === '0') {
            rules.value[item.fieldEnNm].push({ required: true, message: '请输入' + item.fieldCnNm, trigger: 'blur' })
        }
        if (item.fieldType === '2') {
            rules.value[item.fieldEnNm].push({ pattern: /^[+-]?(0|([1-9]\d*))(\.\d+)?$/, message: '请输入数字格式', trigger: 'blur' })
        } else if (item.fieldType === '6') {
            item.pictureList = []
            item.dialogImageUrl = ''
            item.dialogVisible = false
        } else if (item.fieldType === '7') {
            item.fileList = []
        } else if (item.fieldType === '8' || item.fieldType === '9') {
            item.options = await getDict(item.fieldConf)
        } else if (item.fieldType === '11') {
            form.value[item.fieldEnNm] = []
            item.tableFields.forEach(async tableField => {
                if (tableField.fieldType === '8' || tableField.fieldType === '9') {
                    tableField.options = await getDict(tableField.fieldConf)
                }
            })
        }
    })
}
//预览
const preview = (data) => {
    dialogFormVisible.value = true
    disabledSubmit.value = true
    fields.value = JSON.parse(JSON.stringify(data))
    handleField(fields.value)
}

const beforeAvatarUpload = (uploadFile, type) => {
    if (type) {
        const isJPG = (uploadFile.type === 'image/jpeg') || (uploadFile.type === 'image/png');
        if (!isJPG) {
            ElMessage.error('上传图片只能是JPG/PNG格式!');
            return false;
        }
    }
    const isLt5M = uploadFile.size / 1024 / 1024 < 5;
    if (!isLt5M) {
        ElMessage.error('上传文件大小不能超过5MB!');
        return false;
    }
    return true
}

const handlePictureCardPreview = (uploadFile, id) => {
    fields.value.forEach(item => {
        if (item.id === id) {
            item.dialogImageUrl = uploadFile.url
            item.dialogVisible = true
        }
    })
}

const handleRemove = (uploadFile, uploadFiles, fieldEnNm) => {
    const value = uploadFiles.map(item => item.response.data).join(',');
    form.value[fieldEnNm] = value
}

const handleAvatarSuccess = (res, uploadFile, uploadFiles, fieldEnNm) => {
    if (res.code === 200) {
        const value = uploadFiles.map(item => item.response.data).join(',');
        form.value[fieldEnNm] = value
    } else {
        uploadFiles.pop()
        ElMessage.error(res.msg)
    }
}

const getDict = async (dictCode) => {
    const res = await api.get('/system/dict/getDictItems', { dictCode })
    if (res.data.code === 200) {
        return res.data.data
    } else {
        ElMessage.error(res.msg)
        return null
    }
}

const submit = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            wf.value.initStart(definitionId.value, instanceId.value, form.value)
        }
    })
}

onMounted(() => {
    const str = window.localStorage.getItem("access-admin")
    const user = JSON.parse(str)
    const token = Decrypt(user.token)
    header.value = { token: token, accessAuthor: 'allow' }
})
defineExpose({
    init,
    preview
});
</script>